package com.lzgcoding.onlineshopapp.feature.main.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lzgcoding.onlineshopapp.room.dao.BannerDao
import com.lzgcoding.onlineshopapp.room.dao.CategoryDao
import com.lzgcoding.onlineshopapp.room.dao.ItemDao
import com.lzgcoding.onlineshopapp.room.entity.CategoryEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn

class DashboardViewModel(
    private val bannerDao: BannerDao,
    private val itemDao: ItemDao,
    private val categoryDao: CategoryDao
) : ViewModel() {
    private val _uiState = MutableStateFlow(DashboardUIState())
    val uiState: StateFlow<DashboardUIState> = _uiState.onStart {
        initData()
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _uiState.value)

    private suspend fun initData() {
        val categories = categoryDao.getAll()
        val banners = bannerDao.getAll()
        val populars = itemDao.getAll()
        _uiState.value = DashboardUIState(
            categories = categories,
            banners = banners,
            populars = populars
        )
    }

    fun onSearchValueChange(value: String) {
        _uiState.value = _uiState.value.copy(searchValue = value)
    }

    fun onCategorySelected(category: CategoryEntity) {
        _uiState.value = _uiState.value.copy(selectedCategoryId = category.id)
    }
}